package com.bocai.controller;

import com.bocai.bean.CompetitionHot;
import com.bocai.bean.CustomEvent;
import com.bocai.bean.OrderInfo;
import com.bocai.bean.TCMObject;
import com.bocai.service.ICompetitionService;
import com.bocai.service.ICustomEventService;
import com.bocai.service.IOrderService;
import com.bocai.utils.*;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.math.BigDecimal;
import java.text.ParseException;
import java.util.*;

@Controller
@RequestMapping("order")
public class OrderController {

    @Autowired
    private IOrderService orderService;

    @Autowired
    private ICustomEventService customEventService;

    @Autowired
    private ICompetitionService competitionService;

    /**
    @ApiOperation(value = "下单", notes = "")
    @RequestMapping(value = "placeOrder", method = RequestMethod.GET)
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "userId", dataType = "int", required = true, value = "用户id", defaultValue = "15"),
            @ApiImplicitParam(paramType = "query", name = "accountId", dataType = "string", required = true, value = "账户id", defaultValue = "ac67f2bb-45d5-4ac7-b30f-1fc55821f3aa"),
            @ApiImplicitParam(paramType = "query", name = "eventId", dataType = "int", required = true, value = "比赛id", defaultValue = "1504400"),
            @ApiImplicitParam(paramType = "query", name = "marketId", dataType = "int", required = true, value = "市场id", defaultValue = "6568104"),
            @ApiImplicitParam(paramType = "query", name = "ruleTypeId", dataType = "int", required = true, value = "玩法id", defaultValue = "1"),
            @ApiImplicitParam(paramType = "query", name = "selectionId", dataType = "int", required = true, value = "选项id", defaultValue = "1"),
            @ApiImplicitParam(paramType = "query", name = "v1", dataType = "double", required = true, value = "Market Selection V1", defaultValue = "0"),
            @ApiImplicitParam(paramType = "query", name = "v2", dataType = "double", required = true, value = "Market Selection V2", defaultValue = "0"),
            @ApiImplicitParam(paramType = "query", name = "v3", dataType = "double", required = true, value = "Market Selection V3", defaultValue = "0"),
            @ApiImplicitParam(paramType = "query", name = "placedResult", dataType = "string", required = true, value = "盘中验证，回填 Market VerifyResult", defaultValue = "0,0"),
            @ApiImplicitParam(paramType = "query", name = "requestPrice", dataType = "double", required = true, value = "下单价格，买单为 BackOdds", defaultValue = "2.14"),
            @ApiImplicitParam(paramType = "query", name = "requestAmount", dataType = "double", required = true, value = "下单金额，买单为正数,范围：0 < 投注额度 <= 市场的:MaxStakeLimit", defaultValue = "100"),
            @ApiImplicitParam(paramType = "query", name = "homeTeam", dataType = "string", required = true, value = "主队名称", defaultValue = "中国"),
            @ApiImplicitParam(paramType = "query", name = "awayTeam", dataType = "string", required = true, value = "客队名称", defaultValue = "日本"),
            @ApiImplicitParam(paramType = "query", name = "competitionName", dataType = "string", required = true, value = "赛事名称", defaultValue = ""),
    })

    @ResponseBody
    public ResponseData placeOrder(Integer userId,
                                   String accountId,
                                   Integer eventId,
                                   Integer marketId,
                                   Integer ruleTypeId,
                                   Integer selectionId,
                                   Double v1,
                                   Double v2,
                                   Double v3,
                                   String placedResult,
                                   BigDecimal requestPrice,
                                   BigDecimal requestAmount,
                                   String homeTeam,
                                   String awayTeam,
                                   String competitionName) {

        ResponseData data = new ResponseData();
        data.setCodeEnum(CodeEnum.SUCCESS);

        return orderService.placeOrder(userId,
                accountId,
                eventId,
                marketId,
                ruleTypeId,
                selectionId,
                v1,
                v2,
                v3,
                placedResult,
                requestPrice,
                requestAmount,
                homeTeam,
                awayTeam,
                competitionName,
                data);

    }
     */

    @ApiOperation(value = "获取客户国家或者赛事页比赛数据列表", notes = "")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "countryId", dataType = "int", required = false, value = "国家id", defaultValue = ""),
            @ApiImplicitParam(paramType = "query", name = "competitionId", dataType = "int", required = false, value = "赛事id", defaultValue = ""),
    })
    @RequestMapping(value = "getEventList", method = RequestMethod.GET)
    @ResponseBody

    public ResponseData getEventList(Integer countryId, Integer competitionId) {

        ResponseData data = new ResponseData();

        //验证参数，必须传一个
        if (ObjUtils.isEmpty(countryId) && ObjUtils.isEmpty(competitionId)) {
            data.setCodeEnum(CodeEnum.CODE_90002);
            return data;
        }

        Map<String, Object> eventListParame = new HashMap<>();
        eventListParame.put("language", SysConstant.LANGUAGE_TYPE);
        eventListParame.put("sportId", "1");

        if (ObjUtils.isNotEmpty(countryId)) {
            eventListParame.put("countryId", countryId);
        }

        if (ObjUtils.isNotEmpty(competitionId)) {
            //判断该赛事是否被禁用
            Integer isEnable = competitionService.selectHotCompetitionId(competitionId).getIsEnable();

            if (isEnable == 1) {
                //该赛事被禁止
                data.setResults(CodeEnum.CODE_30003);
                return data;
            }

            eventListParame.put("competitionId", competitionId);
        }

        Long beginTime = new Date().getTime() - 90 * 60 * 1000;
        Long endTime = new Date().getTime() + 3 * 24 * 60 * 60 * 1000;

        eventListParame.put("beginTime", beginTime);
        eventListParame.put("endTime", endTime);

        //请求比赛列表
        JSONArray eventList = null;

        try {
            eventList = GetResultUtils.getObject(SysConstant.EVENT_LIST, eventListParame).getBody().getJSONArray("data");
        } catch (Exception e) {
            e.printStackTrace();
            data.setCodeEnum(CodeEnum.CODE_1);
            return data;
        }

        for (int i = 0; i < eventList.size(); i++) {
            JSONObject eventInfo = eventList.getJSONObject(i);
            Integer eventId = eventInfo.getInt("eventId");

            //判断该比赛状态，只留下没有结束的比赛
            Integer state = eventInfo.getInt("state");

            if (state.equals(EventState.Finished.getValue()) ||
                    state.equals(EventState.Cancelled.getValue()) ||
                    state.equals(EventState.Abandoned.getValue())) {
                continue;
            }

            //判断该比赛是否被禁用
            CustomEvent customEvent = customEventService.selectEvent(eventId);
            if (null != customEvent && customEvent.getIsEnable() == 1) {
                continue;//被禁用，放弃此比赛
            }

            //查询比赛的市场

            Map<String, Object> marketListParame = new HashMap<>();
            marketListParame.put("eventId", eventId);

            JSONArray marketList = null;
            try {
                marketList = GetResultUtils.getObject(SysConstant.EVENT_MARKETS, marketListParame).getBody().getJSONArray("data");
            } catch (Exception e) {
                e.printStackTrace();
                continue;
            }

            //获取这个比赛被禁用的玩法
            List<String> ruleTypes = new ArrayList<>();

            if (null != customEvent && null != customEvent.getRuleTypes()) {
                ruleTypes.addAll(Arrays.asList(customEvent.getRuleTypes().split(",")));
            }

            //可以玩的市场个数
            Integer marketCount = 0;

            for (int j = 0; j < marketList.size() ; j++) {

                JSONObject marketInfo = marketList.getJSONObject(j);

                Integer ruleType = marketInfo.getInt("ruleType");
                Integer periodType = marketInfo.getInt("periodType");
                Integer marketState = marketInfo.getInt("state");

                //处理胜平负玩法，并且胜平负市场没有关闭
                if (ruleType.equals(FootballRuleType.MATCH_ODDS.getValue())) {
                    //判断玩法是否被禁用
                    if (!ruleTypes.contains(FootballRuleType.MATCH_ODDS.getValue() + "") &&
                            marketState.equals(MarketState.MarketState_Open.getStatus()) &&
                            periodType.equals(FootballPeriodType.PeriodType_FullTime.getValue())) {
                        marketCount++;
                        eventInfo.put("market", marketInfo);
                        continue;
                    }
                }

                //入球单双数
                if (ruleType.equals(FootballRuleType.ODD_EVEN.getValue())) {
                    if (!ruleTypes.contains(FootballRuleType.ODD_EVEN.getValue() + "") &&
                            marketState.equals(MarketState.MarketState_Open.getStatus()) &&
                            periodType.equals(FootballPeriodType.PeriodType_FullTime.getValue()))
                        marketCount++;
                    continue;
                }
                //正确比分
                if (ruleType.equals(FootballRuleType.CORRECT_SCORE.getValue())) {
                    if (!ruleTypes.contains(FootballRuleType.CORRECT_SCORE.getValue() + "") &&
                            marketState.equals(MarketState.MarketState_Open.getStatus()) &&
                            periodType.equals(FootballPeriodType.PeriodType_FullTime.getValue()))
                        marketCount++;
                    continue;
                }
                //下一个进球
                if (ruleType.equals(FootballRuleType.NEXT_TEAM_TO_SCORE.getValue())) {
                    if (!ruleTypes.contains(FootballRuleType.NEXT_TEAM_TO_SCORE.getValue() + "") &&
                            marketState.equals(MarketState.MarketState_Open.getStatus()) &&
                            periodType.equals(FootballPeriodType.PeriodType_Dynamic.getValue()))
                        marketCount++;
                    continue;
                }
                //准确进球数
                if (ruleType.equals(FootballRuleType.EXACT_GOALS.getValue())) {
                    if (!ruleTypes.contains(FootballRuleType.EXACT_GOALS.getValue() + "") &&
                            marketState.equals(MarketState.MarketState_Open.getStatus()) &&
                            periodType.equals(FootballPeriodType.PeriodType_FullTime.getValue()))
                        marketCount++;
                    continue;
                }
            }

            eventInfo.put("marketCount", marketCount);
        }

        data.setResults(eventList);

        return data;
    }

    @ApiOperation(value = "获取比赛市场列表", notes = "1497183")
    @RequestMapping(value = "getMarketList", method = RequestMethod.GET)
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "eventId", dataType = "int", required = true, value = "比赛id", defaultValue = ""),
            @ApiImplicitParam(paramType = "query", name = "evented", dataType = "int", required = false, value = "是否需要包含比赛详情1需要，0不需要", defaultValue = ""),
            @ApiImplicitParam(paramType = "query", name = "opend", dataType = "int", required = false, value = "是否需要包含关闭的市场1需要，0不需要", defaultValue = ""),
            @ApiImplicitParam(paramType = "query", name = "enabled", dataType = "int", required = false, value = "是否需要禁用的市场1需要，0不需要,暂时没用到", defaultValue = ""),
    })
    @ResponseBody
    public ResponseData getMarketList(Integer eventId,
                                      Integer evented,
                                      Integer opend,
                                      Integer enabled) {

        ResponseData data = new ResponseData();
        data.setCodeEnum(CodeEnum.SUCCESS);

        CodeEnum codeEnum = ObjUtils.validateParams(new Object[]{eventId});
        if (ObjUtils.isNotEmpty(codeEnum)) {
            data.setCodeEnum(CodeEnum.CODE_90001);
            return data;
        }

        Map<String, JSONObject> temp = new HashMap<>();

        if (null != evented && evented == 1) {
            Map<String, Object> map = new HashMap<>();
            map.put("language", SysConstant.LANGUAGE_TYPE);
            map.put("eventId", eventId);

            //获取比赛详情
            TCMObject tcmObject = GetResultUtils.getObject(SysConstant.EVENT_INFO, map);
            JSONObject eventInfo = tcmObject.getBody().getJSONObject("data");

            //获取禁用的市场
            CustomEvent customEvent = customEventService.selectEvent(eventId);

            if (null != customEvent) {
                eventInfo.put("disRuleTypes", customEvent.getRuleTypes());
            }

            temp.put("event", eventInfo);

            Integer state = eventInfo.getInt("state");
            //如果比赛已经结束，不能投注，需要补上结束时间
            if (!(state.equals(EventState.Running.getValue()) ||
                    state.equals(EventState.Open.getValue()))){

                Map<String,Object> casesParame = new HashMap<>();
                casesParame.put("eventId",eventId);
                casesParame.put("language",SysConstant.LANGUAGE_TYPE);

               JSONArray cases = null;

               try{
                   cases = GetResultUtils.getObject(SysConstant.EVENT_CASES,casesParame).getBody().getJSONArray("data");
               }catch (Exception e){
                   e.printStackTrace();
               }

               if (null != cases){
                   JSONObject caseInfo = cases.getJSONObject(cases.size() - 1);
                   Integer caseMinutes = caseInfo.getInt("caseMinutes");
                   eventInfo.put("caseMinutes",caseMinutes + ":00");
               }

               if (0 == opend){
                   data.setResults(temp);
                   return data;
               }
            }
        }

        //处理可投注市场
        Map<String, Object> map = new HashMap<>();
        map.put("eventId", eventId);
        TCMObject tcmObject = GetResultUtils.getObject(SysConstant.EVENT_MARKETS, map);
        if (!tcmObject.getStatus().equals(200)) {
            data.setCodeEnum(CodeEnum.CODE_1);
            return data;
        }

        JSONArray markets = tcmObject.getBody().getJSONArray("data");

        for (int i = 0; i < markets.size(); i++) {
            JSONObject market = markets.getJSONObject(i);

            Integer ruleType = market.getInt("ruleType");
            Integer status = market.getInt("state");
            Integer periodType = market.getInt("periodType");

            //胜平负 开放状态 周期是全场
            if (ruleType.equals(FootballRuleType.MATCH_ODDS.getValue()) &&
                    periodType.equals(FootballPeriodType.PeriodType_FullTime.getValue())) {
                if (null != opend && opend == 1) {
                    temp.put("market100", market);
                } else {
                    if (status.equals(MarketState.MarketState_Open.getStatus())) {
                        temp.put("market100", market);
                    }
                }
                continue;
            }

            //入球单双数 周期是全场
            if (ruleType.equals(FootballRuleType.ODD_EVEN.getValue()) &&
                    periodType.equals(FootballPeriodType.PeriodType_FullTime.getValue())) {
                if (null != opend && opend == 1) {
                    temp.put("market130", market);
                } else {
                    if (status.equals(MarketState.MarketState_Open.getStatus())) {
                        temp.put("market130", market);
                    }
                }
                continue;
            }

            //正确比分 周期是全场
            if (ruleType.equals(FootballRuleType.CORRECT_SCORE.getValue()) &&
                    periodType.equals(FootballPeriodType.PeriodType_FullTime.getValue())) {
                if (null != opend && opend == 1) {
                    temp.put("market140", market);
                } else {
                    if (status.equals(MarketState.MarketState_Open.getStatus())) {
                        temp.put("market140", market);
                    }
                }
                continue;
            }

            //下一个进球 动态周期
            if (ruleType.equals(FootballRuleType.NEXT_TEAM_TO_SCORE.getValue()) &&
                    periodType.equals(FootballPeriodType.PeriodType_Dynamic.getValue())) {
                if (null != opend && opend == 1) {
                    temp.put("market350", market);
                } else {
                    if (status.equals(MarketState.MarketState_Open.getStatus())) {
                        temp.put("market350", market);
                    }
                }
                continue;
            }

            //准确进球数 周期是全场
            if (ruleType.equals(FootballRuleType.EXACT_GOALS.getValue()) &&
                    periodType.equals(FootballPeriodType.PeriodType_FullTime.getValue())) {
                if (null != opend && opend == 1) {
                    temp.put("market410", market);
                } else {
                    if (status.equals(MarketState.MarketState_Open.getStatus())) {
                        temp.put("market410", market);
                    }
                }
                continue;
            }
        }

        data.setResults(temp);
        return data;
    }

    @ApiOperation(value = "投注单管理", notes = "服务端 status0; // 订单待定状态，等待投注延迟结束\n" +
            "1; // 订单正常\n" +
            "2; // 订单已结算\n" +
            " 3; // 订单已被取消\n" +
            " 4; // 订单无效\n" +
            "5; // 订单被拒绝，投注延迟期间发生重要事件等原因")
    @RequestMapping(value = "getOrderManager", method = RequestMethod.GET)
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "userId", dataType = "int", required = false, value = "不传为查询全部", defaultValue = ""),
            @ApiImplicitParam(paramType = "query", name = "date", dataType = "string", required = false, value = "时间yyyy-MM-dd", defaultValue = ""),
            @ApiImplicitParam(paramType = "query", name = "ruleType", dataType = "int", required = false, value = "玩法", defaultValue = ""),
            @ApiImplicitParam(paramType = "query", name = "status", dataType = "int", required = false, value = "状态", defaultValue = ""),
            @ApiImplicitParam(paramType = "query", name = "keyword", dataType = "string", required = false, value = "关键词,手机号，赛事，球队名称", defaultValue = ""),
            @ApiImplicitParam(paramType = "query", name = "eventId", dataType = "int", required = false, value = "比赛id", defaultValue = ""),
    })
    @ResponseBody
    public ResponseData getOrderManager(Integer userId,
                                        String date,
                                        Integer ruleType,
                                        Integer status,
                                        String keyword,
                                        Integer eventId) {

        ResponseData data = new ResponseData();
        data.setCodeEnum(CodeEnum.SUCCESS);

        Map<String, Object> map = new HashMap<>();

        if (date != null) {
            try {
                map.put("beginDate", DateUtils.parse(date + " 00:00:00"));
                map.put("endDate", DateUtils.parse(date + " 23:59:59"));
            } catch (ParseException e) {
                e.printStackTrace();
                data.setCodeEnum(CodeEnum.CODE_90002);
                return data;
            }
        }
        map.put("userId", userId);
        map.put("ruleType", ruleType);
        map.put("status", status);
        if (ObjUtils.isNotEmpty(keyword)) {
            map.put("keyword", keyword);
        }
        map.put("eventId", eventId);
        return orderService.selectOrderManager(map, data);

    }

    @ApiOperation(value = "查询订单列表", notes = "")
    @RequestMapping(value = "getOrderList", method = RequestMethod.GET)
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "userId", dataType = "int", required = true, value = "用户id", defaultValue = ""),
            @ApiImplicitParam(paramType = "query", name = "state", dataType = "int", required = false, value = "订单状态2.已完成,1未完成，不传为全部", defaultValue = ""),
    })
    @ResponseBody
    public ResponseData getOrderList(Integer userId, Integer state) {

        ResponseData data = new ResponseData();
        data.setCodeEnum(CodeEnum.SUCCESS);

        return orderService.selectByUserId(userId, state, data);
    }

    @ApiOperation(value = "服务端使用投注统计", notes = "")
    @RequestMapping(value = "selectOrderCount", method = RequestMethod.GET)
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "eventId", dataType = "int", value = "比赛id", defaultValue = ""),
            @ApiImplicitParam(paramType = "query", name = "ruleType", dataType = "int", value = "玩法", defaultValue = ""),
    })
    @ResponseBody
    public ResponseData selectOrderCount(Integer eventId, Integer ruleType) {
        ResponseData data = new ResponseData();

        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setEventId(eventId);
        orderInfo.setRuleTypeId(ruleType);

        return orderService.selectOrderCount(orderInfo, data);
    }

    @ApiOperation(value = "服务端使用投注统计明细", notes = "")
    @RequestMapping(value = "selectOrderCountDetail", method = RequestMethod.GET)
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "eventId", dataType = "int", value = "比赛id", defaultValue = ""),
            @ApiImplicitParam(paramType = "query", name = "ruleType", dataType = "int", value = "玩法", defaultValue = ""),
            @ApiImplicitParam(paramType = "query", name = "selectionId", dataType = "int", value = "选项id", defaultValue = ""),
    })
    @ResponseBody
    public ResponseData selectOrderCountDetail(Integer eventId, Integer ruleType, Integer selectionId) {
        ResponseData data = new ResponseData();

        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setEventId(eventId);
        orderInfo.setRuleTypeId(ruleType);
        orderInfo.setSelectionId(selectionId);

        return orderService.selectOrderCountDetail(orderInfo, data);
    }

}
